<?php

namespace App\Wxapp\Controllers;

use App\Store\Models\Account\SiteStore;
use App\Store\Models\Member\Member;
use App\Store\Models\Member\MemberBalanceChangelog;
use App\Store\Models\Member\MemberPointsChangelog;
use App\Store\Models\Order\OrderPointschangebalance;
use App\Store\Models\Sysset\Config;
use App\Store\Models\Sysset\Score;
use App\Store\Models\Wxapp\Gift\WxappGiftExchangelog;
use App\Store\Models\Wxapp\Gift\WxappGiftLog;
use App\Store\Models\Wxapp\Gift\WxappGiftStocklist;
use App\Store\Models\Wxapp\WxappCouponCodeList;
use App\Store\Models\Wxapp\WxappSignlog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;

/**
 * 个人中心相关
 */
class MemberController extends BaseController
{

    public function getmeminfo(Request $request){
        $meminfo=Member::query()
            ->where('id',$this->meminfo['id'])
            ->where('is_del',1)
            ->first();
        if(empty($meminfo)){
            return response()->json(['code' => '001', 'msg' => '会员信息不存在']);
        }
        $meminfo = $meminfo->toArray();
        $couponcount=WxappCouponCodeList::where(['cp_id' => $this->cp_id,'mem_id'=>$meminfo['id'],'is_used'=>1,'is_receive'=>2])->where('available_end_time','>=',time())->count();

        $up_days_json=Redis::get('wxapp_signlog_up_days_'.$this->meminfo['id']);
        $up_days_arr=$up_days_json?json_decode($up_days_json,true):[];
        $up_days=0;
        if(is_array($up_days_arr) && $up_days_arr){
            if(strtotime($up_days_arr['last_sign_date'])==strtotime('yesterday') || strtotime($up_days_arr['last_sign_date'])==strtotime(date('Y-m-d'))){
                $up_days=$up_days_arr['up_days'];
            }
        }

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['meminfo' => $meminfo,'couponcount'=>$couponcount,'up_days'=>$up_days]]);
    }

    public function bindoutwxaccount(Request $request){

        Member::where('id',$this->meminfo['id'])->update(['wx_account_open_id'=>'','is_band_wxaccount'=>1]);
        return response()->json(['code' => '000', 'msg' => '解绑成功']);
    }


    public function changerealname(Request $request){
        $real_name=$request->real_name ?? '';

        if($real_name==''){
            return response()->json(['code' => '001', 'msg' => '姓名不能为空']);
        }
        Member::where('id',$this->meminfo['id'])->update(['real_name'=>$real_name]);
        $token = $request->header('token');
        $meminfo=Member::where('id',$this->meminfo['id'])->first();
        Redis::set($token,json_encode($meminfo));
        return response()->json(['code' => '000', 'msg' => '更改成功']);
    }

    protected function getpointssetting(){
        $pointssetting=Redis::get('pointssetting_'.$this->cp_id);
        if(!$pointssetting){
            $pointssetting=Config::where(['config_key'=>'sign_in','cp_id'=>$this->cp_id])->value('config_val');
            $pointssetting && Redis::set('pointssetting_'.$this->cp_id,$pointssetting);
        }
        $pointssetting=json_decode($pointssetting,true);
        return $pointssetting;
    }


    public function getpointssettinginfo(){

        $pointssetting=$this->getpointssetting();
        return response()->json(['code' => '000', 'msg' => '获取成功','data'=>['pointssetting'=>$pointssetting]]);
    }

    public function pointstobalance(Request $request){


        $meminfo=Member::where('id',$this->meminfo['id'])->first()->toArray();

        $points=intval($request->points);
        if($points<=0){
            return response()->json(['code' => '001', 'msg' => '积分不可小于0']);
        }

        if($meminfo['points_current']<$points){
            return response()->json(['code' => '001', 'msg' => '积分不足']);
        }
        $pointssetting=$this->getpointssetting();
        $pointstobalance_ratio=$pointssetting['rate'];
        $money=intval($points/$pointstobalance_ratio*100);


        $balancelogdata=[
            'cp_id'=>$this->cp_id,
            'mem_id'=>$this->meminfo['id'],
            'type'=>3,
            'store_id'=>$this->meminfo['store_id'],
            'change_val'=>$money,
            'change_before'=>$meminfo['pointstobalance'],
            'change_after'=>$meminfo['pointstobalance']+$money,
            'loginfo'=>json_encode(['title'=>'积分转预存']),
            'create_at' => time(),
            'update_at' => time(),
        ];

        $pointslogdata=[
            'cp_id'=>$this->cp_id,
            'mem_id'=>$this->meminfo['id'],
            'type'=>5,
            'store_id'=>$this->meminfo['store_id'],
            'change_val'=>-$points,
            'change_before'=>$meminfo['points_current'],
            'change_after'=>$meminfo['points_current']-$points,
            'loginfo'=>json_encode(['title'=>'积分转预存']),
            'create_at' => time(),
            'update_at' => time(),
        ];

        DB::beginTransaction();
        try {
            MemberBalanceChangelog::create($balancelogdata);
            MemberPointsChangelog::create($pointslogdata);
            Member::where(['id' => $this->meminfo['id'], 'cp_id' => $this->cp_id, 'is_del' => 1])->update([
            'pointstobalance'=> DB::raw('pointstobalance + ' . ($money)),
            'points_current'=> DB::raw('points_current - ' . $points),
            'points_used'=> DB::raw('points_used + ' . $points),
            ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '积分转预存操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '积分转预存操作成功']);


    }
    /**
     * 积分签到
     */
    public function dopointssign(Request $request){

        $sign_date=date('Y-m-d');
        $meminfo=Member::where('id',$this->meminfo['id'])->first()->toArray();
        $issign=WxappSignlog::where(['mem_id' => $this->meminfo['id'], 'cp_id' => $this->cp_id,'sign_date'=>$sign_date])->first();
        if($issign){
            return response()->json(['code' => '001', 'msg' => '今日已签到']);
        }
        $up_days_json=Redis::get('wxapp_signlog_up_days_'.$this->meminfo['id']);
        $up_days_arr=$up_days_json?json_decode($up_days_json,true):[];

        if(is_array($up_days_arr) && $up_days_arr){
            if(strtotime($up_days_arr['last_sign_date'])==strtotime('yesterday')){

                $up_days=$up_days_arr['up_days']+1;
            }else{

                $up_days=1;
            }
        }else{
            $up_days=1;
        }

        $pointssetting=$this->getpointssetting();
        $points=isset($pointssetting['day_'.$up_days])?$pointssetting['day_'.$up_days]:0;
        if($points<=0){
            return response()->json(['code' => '001', 'msg' => '签到失败']);
        }
        $signlog=[
            'cp_id'=>$this->cp_id,
            'mem_id'=>$this->meminfo['id'],
            'sign_date'=>$sign_date,
            'points'=>$points,
            'up_days'=>$up_days,
            'sign_at'=>time(),
        ];
        Log::info('points:'.$points);
        Log::info('signlog:'.json_encode($signlog));
        $pointslogdata=[
            'cp_id'=>$this->cp_id,
            'mem_id'=>$this->meminfo['id'],
            'type'=>6,
            'store_id'=>$this->meminfo['store_id'],
            'change_val'=>$points,
            'change_before'=>$meminfo['points_current'],
            'change_after'=>$meminfo['points_current']+$points,
            'create_at' => time(),
            'update_at' => time(),
        ];
        Log::info('signlog:'.json_encode($pointslogdata));
        DB::beginTransaction();
        try {
            WxappSignlog::create($signlog);
            MemberPointsChangelog::create($pointslogdata);
            Member::where(['id' => $this->meminfo['id'], 'cp_id' => $this->cp_id, 'is_del' => 1])->update([
            'points_current'=> DB::raw('points_current + ' . $points),'points_total'=> DB::raw('points_total + ' . $points),
            ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '签到失败' . $e->getMessage()]);
        }

        Redis::set('wxapp_signlog_up_days_'.$this->meminfo['id'],json_encode(['up_days'=>$up_days,'last_sign_date'=>$sign_date]));

        return response()->json(['code' => '000', 'msg' => '签到成功']);


    }

    public function getpointsupdays(Request $request){
        $up_days_json=Redis::get('wxapp_signlog_up_days_'.$this->meminfo['id']);
        $up_days_arr=$up_days_json?json_decode($up_days_json,true):[];
        if(is_array($up_days_arr) && $up_days_arr){
            if(strtotime($up_days_arr['last_sign_date'])==strtotime('yesterday') || strtotime($up_days_arr['last_sign_date'])==strtotime(date('Y-m-d'))){
                $up_days=$up_days_arr['up_days'];

                $list=WxappSignlog::where(['mem_id'=>$this->meminfo['id']])->orderBy('sign_at','desc')->limit($up_days)->get()->toArray();



            }else{

                $list=[];
            }
        }else{
            $list=[];
        }

        return response()->json(['code' => '000', 'msg' => '获取成功','data'=>['list'=>$list]]);


    }



    /**
     * 积分记录
     */
    public function pointslog(Request $request){
        $list=MemberPointsChangelog::getListByMem($request,$this->cp_id,$this->meminfo['id']);
        return response()->json(['code' => '000', 'msg' => '获取成功','data'=>$list]);
    }
    /**
     * 礼品列表
     */
    public function getgiftlist(Request $request){
        $list=WxappGiftStocklist::getListByMem($request,$this->cp_id,$this->meminfo['id']);
        return response()->json(['code' => '000', 'msg' => '获取成功','data'=>$list]);
    }
    /**
     * 获取礼品支持的兑换门店
     */
    public function getstoreidwithgiftlist(Request $request){
        $gift_id=intval($request->gift_id);
        $store_ids=WxappGiftStocklist::where([['is_del',1],['cp_id',$this->cp_id],['store_id','<>',0],['gift_id',$gift_id],['current_count','>',0],['audit_status',2]])->pluck('store_id');
        $list=SiteStore::where([['cp_id',$this->cp_id]])->whereIn('id',$store_ids)->get();
        return response()->json(['code' => '000', 'msg' => '获取成功','data'=>['list'=>$list]]);
    }



    /**
     * 兑换记录
     */
    public function pointsexchangelog(Request $request){
        $list=WxappGiftExchangelog::getListByMem($request,$this->cp_id,$this->meminfo['id']);
        return response()->json(['code' => '000', 'msg' => '获取成功','data'=>$list]);
    }

    /**
     * 积分兑换
     */
    public function pointsexchange(Request $request){
        $gift_id=intval($request->gift_id);
        $store_id=intval($request->store_id);
        $meminfo=Member::where('id',$this->meminfo['id'])->first()->toArray();
        $storeinfo=SiteStore::where([['cp_id',$this->cp_id]])->where('id',$store_id)->first();
        if(!$storeinfo){
            return response()->json(['code' => '001', 'msg' => '门店不存在']);
        }
        $giftinfo=WxappGiftStocklist::where([['is_del',1],['cp_id',$this->cp_id],['store_id',$store_id],['gift_id',$gift_id],['audit_status',2],['current_count','>',0]])->first();
        if(!$giftinfo){
            return response()->json(['code' => '001', 'msg' => '礼品库存不存在']);
        }
        if($giftinfo->need_points>$meminfo['points_current']){
            return response()->json(['code' => '001', 'msg' => '积分不足']);
        }
        if($giftinfo->current_count<=0){
            return response()->json(['code' => '001', 'msg' => '库存不足']);
        }


        if($giftinfo->valid_end_at!=0 && $giftinfo->valid_end_at<time()){
            return response()->json(['code' => '001', 'msg' => '超出兑换有效期']);
        }

        if($giftinfo->piecelimit>0){
            $count=WxappGiftExchangelog::where([['cp_id',$this->cp_id],['store_id',$store_id],['gift_id',$gift_id],['mem_id',$this->meminfo['id']]])->count();
            if($count>=$giftinfo->piecelimit){
                return response()->json(['code' => '001', 'msg' => '已超限制']);
            }
        }

        $pointslogdata=[
            'cp_id'=>$this->cp_id,
            'mem_id'=>$this->meminfo['id'],
            'type'=>11,
            'store_id'=>$store_id,
            'change_val'=>-$giftinfo->need_points,
            'change_before'=>$meminfo['points_current'],
            'change_after'=>$meminfo['points_current']-$giftinfo->need_points,
            'loginfo'=>json_encode(['title'=>'兑换礼品:'.$giftinfo->gift_name]),
            'create_at' => time(),
            'update_at' => time(),
        ];
        $exchangelog=[
            'cp_id'=>$this->cp_id,
            'store_id'=>$store_id,
            'mem_id'=>$this->meminfo['id'],
            'gift_id'=>$gift_id,
            'gift_name'=>$giftinfo->gift_name,
            'gift_info'=>json_encode($giftinfo),
            'count'=>1,
            'points'=>$giftinfo->need_points,
            'create_at'=>time(),
            'update_at'=>time(),
        ];

        $data=[
            'cp_id'=>$this->cp_id,
            'gift_id'=>$gift_id,
            'gift_name'=>$giftinfo->gift_name,
            'count'=>1,
            'type'=>4,
            'store_id'=>$store_id,
            'create_account_id'=>0,
            'create_account_real_name'=>'',
            'update_account_id'=>0,
            'update_account_real_name'=>'',
            'create_at'=>time(),
            'update_at'=>time(),
            'remark'=>'',
            'start_store_id'=>$store_id,
            'target_store_id'=>0,
        ];


        DB::beginTransaction();
        try {
            WxappGiftLog::create($data);
            MemberPointsChangelog::create($pointslogdata);
            WxappGiftExchangelog::create($exchangelog);
            Member::where(['id' => $this->meminfo['id'], 'cp_id' => $this->cp_id, 'is_del' => 1])->update([
            'points_current'=> DB::raw('points_current - ' . $giftinfo->need_points),
            'points_used'=> DB::raw('points_used + ' . $giftinfo->need_points),
            ]);
            WxappGiftStocklist::where([['is_del',1],['cp_id',$this->cp_id],['store_id',$store_id],'gift_id'=>$gift_id])->decrement('current_count');
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '兑换失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '兑换成功']);

    }

    /**
     *  用户绑定门店
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function memPerfect(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
        ], [
            'store_id.required' => '请选择门店',
        ]);

        $id = $this->meminfo['id']?? 0;
        if ($validator->fails()) {
            $msg = $validator->errors()->first();
            return response()->json(['code' => '001', 'msg' => $msg]);
        }
        $params = $validator->validated();

        $meminfo=Member::query()
            ->where('id',$id)
            ->where('is_del',1)
            ->first();
        if(empty($meminfo)){
            return response()->json(['code' => '001', 'msg' => '用户信息不存在']);
        }
        $storeId = $meminfo->store_id?? 0;
        if($storeId>0){
            return response()->json(['code' => '001', 'msg' => '用于已经绑定门店']);
        }

        Member::query()
            ->where('id',$id)
            ->where('is_del',1)
            ->update(['store_id'=>$params['store_id']]);

        $storeId = $meminfo->store_id>0?$meminfo->store_id:$params['store_id'];
        $s_value=Score::where(['cp_id'=>$meminfo->cp_id,'type'=>2,'is_del'=>1])->orderBy('update_at','desc')->value('value')??0;



        $pointslogdata=[
            'cp_id'=>$meminfo->cp_id,
            'mem_id'=>$meminfo->id,
            'type'=>1,
            'store_id'=>$storeId,
            'change_val'=>$s_value,
            'change_before'=>$meminfo->points_current,
            'change_after'=>$meminfo->points_current+$s_value,
            'sales_account_id'=>0,
            'loginfo'=>json_encode(['title'=>'注册赠送']),
            'create_account_id' => 0,
            'update_account_id' =>0,
            'create_account_real_name' => '微信用户注册',
            'update_account_real_name' => '',
            'create_at' => time(),
            'update_at' => time(),
            'remark'=>'注册赠送',
        ];
        MemberPointsChangelog::query()->create($pointslogdata);

        return response()->json(['code' => '000', 'msg' => '保存成功']);

    }






}
